package com.nbjtjc.safe.service.sys;

import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.oss.service.OSSFactory;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SysFileService {
    private static Logger logger= LoggerFactory.getLogger(SysFileService.class);
    @Autowired
    private SysFileMapper sysFileMapper;
    @Autowired
    private FileUtil fileUtil;

    @Lazy
    @Autowired
    private OSSFactory ossFactory;

    public Result<SysFile> uploadFile(MultipartFile multipartFile, SysFile pic) {
        Result result = new Result();
        String filePath = fileUtil.getFilePath();
        java.io.File targetFile = new java.io.File(filePath + multipartFile.getOriginalFilename());
        BufferedOutputStream bufferedOutputStream = null;
        try {
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            //图片格式是png 转换成jpg
            if( Pattern.compile(".+(.PNG|.png)$").matcher(multipartFile.getOriginalFilename()).find()) {
                targetFile=fileUtil.convertPng2Jpg(multipartFile);
            }else{
                multipartFile.transferTo(targetFile);
            }
            pic.setFileName(targetFile.getName());
            pic.setPath(filePath);
            pic.setUploadTime(new Date());
            pic.setUserId(MyShiroUtils.getSessionUserId());
            int res = sysFileMapper.insert(pic);
            if (res == 0) {
                result.setFalse("插入失败");
                return result;
            }
            compare(targetFile,pic.getPercentage());
            result.setData(pic);
        } catch (IOException e) {
            e.printStackTrace();
            result.setFalse("io错误" + e.getMessage());
        }
        return result;
    }

    public SysFile uploadFile(String url,String fileName,SysFile pic){

        pic.setFileName(fileName);
        pic.setPath(url);
        pic.setUploadTime(new Date());
        pic.setUserId(MyShiroUtils.getSessionUserId());
        int res = sysFileMapper.insert(pic);
        if(res==0){
            logger.error("上传失败："+fileName+":url:"+url+"file:"+pic.toString());
        }
        return pic;
    }

    public SysFile add(SysFile sysFile){
        sysFileMapper.insert(sysFile);
        return sysFile;
    }
    /**
     * 压缩图片
     *
     * @param file
     * @param percentage 压缩的比例  0.6
     *
     */
    private void compare(File file, Float percentage) throws IOException {
        String reg = ".+(.JPEG|.jpeg|.JPG|.jpg|.PNG|.png)$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(file.getName());
        if (!matcher.find()) {
            return;
        }
        String targetFilePath = file.getAbsolutePath()
                .substring(0, file.getAbsolutePath().lastIndexOf('.'))
                +'_'+(int)(percentage*100)+ file.getAbsolutePath()
                .substring(file.getAbsolutePath().lastIndexOf('.'), file.getAbsolutePath().length());
        File scaleFile = new File(targetFilePath);
//        ImageUtil.scale(file, scaleFile, percentage);
        Thumbnails.of(file).scale(0.25).toFile(scaleFile);

    }

    public SysFile findFile(SysFile sysFile) {
        SysFile file = sysFileMapper.selectOne(sysFile);
        return file;
    }

    @Transactional
    public boolean delete(SysFile sysFile) {
        if (ObjectUtil.isNull(sysFile)
                || ObjectUtil.isNull(sysFile.getfId()))
            return false;
        sysFile = sysFileMapper.selectByPrimaryKey(sysFile.getfId());
        if (sysFile == null)
            return false;
        try {
            ossFactory.build().delete(sysFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除阿里云上存储的文件失败",e);
        }
        String path = sysFile.getPath() + sysFile.getFileName();
        java.io.File targetFile = new java.io.File(path);
        if (targetFile.exists()) {
            if (!targetFile.delete())
                return false;
        }
        sysFileMapper.delete(sysFile);
        return true;
    }

    public Result<SysFile> update(SysFile sysFile) {
        Result<SysFile> result = new Result<>();
        if (ObjectUtil.isNull(sysFile) ||
                ObjectUtil.isNull(sysFile.getfId())) {
            result.setFalse("更新数据不能为空");
            return result;
        }
        int res = sysFileMapper.updateByPrimaryKeySelective(sysFile);
        if (res == 0) {
            result.setFalse("有更新失败");
        }
        result.setData(sysFile);
        return result;
    }
}
